<script lang="ts" setup>
  import { PropType, ref, watch } from 'vue'
  import { getGoodsStock } from '@/api/store'
  import { getOrderNetworkAddress, getWorkUserAddress } from '@/api/parts'
  import { orderAnnexUpload } from '@/api/upload'
  import SingleAddress from '@/components/address/singleAddress.vue'
  import { UploadFile, UploadRawFile } from 'element-plus'
  import _ from 'lodash'
  import uploadPlaceholderImg from '@/assets/image/avatar_upload_default.png'
  import { HMessage, HMessageBox } from '@/components/common/message'
  import { useGetNetworkWarehouse } from '@/services/pages/storage/useWarehouse'
  import {
    useGetWarehouseAndPersonAddressList,
    useGetWarehousePositionOptionList,
  } from '@/services/pages/storage/useWarehouseOut'
  import { useGetGoodList } from '@/services/pages/good/useGood'
  import { useGetGoodSpecService } from '@/services/module/product/useProduct'
  import {
    useGetMaterialDetailSparePartList,
    useOrderSparePartCheckService,
  } from '@/services/pages/order/useSpare'
  import { useGetOrderSparePartInfoBeforeCheck } from '@/services/module/order/useSparePart'

  const {
    warehousePositionOptionList: returnWarehousePositionOptionList,
    getWarehousePositionOptionListParam: getReturnWarehousePositionOptionListParam,
    getWarehousePositionOptionListLoaing: getReturnWarehousePositionOptionListLoading,
    getWarehousePositionOptionList: getReturnWarehousePositionOptionList,
  } = useGetWarehousePositionOptionList()
  const {
    list: returnWarehouseOptionList,
    getListParam: getReturnWarehouseOptionListParam,
    getListLoading: getReturnWarehouseOptionListLoading,
    getList: getReturnWarehouseOptionList,
  } = useGetWarehouseAndPersonAddressList()
  const {
    warehousePositionOptionList: outBoundWarehousePositionOptionList,
    getWarehousePositionOptionListParam: getOutBoundWarehousePositionOptionListParam,
    getWarehousePositionOptionListLoaing: getOutBoundWarehousePositionOptionListLoading,
    getWarehousePositionOptionList: getOutBoundWarehousePositionOptionList,
  } = useGetWarehousePositionOptionList()
  const {
    list: outBoundWarehouseOptionList,
    getListParam: getOutBoundWarehouseOptionListParam,
    getListLoading: getOutBoundWarehouseOptionListLoading,
    getList: getOutBoundWarehouseOptionList,
  } = useGetWarehouseAndPersonAddressList()
  const { list, getListLoading, getList } = useGetMaterialDetailSparePartList()
  const { info, getInfoLoading, getInfo } = useGetOrderSparePartInfoBeforeCheck()
  const { checkForm, checkLoading, check, resetCheckForm } = useOrderSparePartCheckService()
  const { goodList, getGoodListParam, getGoodListLoading, getGoodList } = useGetGoodList()
  const { warehouse, getWarehouse } = useGetNetworkWarehouse()
  const { goodSpecList, getGoodSpecParam, getGoodSpecLoading, getProductSpecList } =
    useGetGoodSpecService()

  defineOptions({
    name: 'OrderDetailSparePartCheckModal',
  })

  const props = defineProps({
    partsId: {
      type: String,
      required: true,
    },
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update-list'): void
  }>()

  // 弹窗显示状态
  const visible = defineModel('modelValue', { type: Boolean, default: false })

  // 附件列宽
  const annexColumnWidth = ref(130)

  // 地址选择组件实例
  const singleAddressInstance = ref<InstanceType<typeof SingleAddress> | null>(null)

  // 地址选择组件双向绑定
  const singleAddressModelValue = ref({
    province: '',
    city: '',
    area: '',
    town: '',
  })

  // 配件选择弹出框显示状态列表
  const sparePartSelectPopoverVisibleList = ref<Array<boolean>>([])

  // 规格下拉选项列表（表格每行的规格下拉选项）
  const sparePartSpecOptionList = ref<Array<Array<ProductAPIResponse.ProductSpec>>>([])

  // 表格每行的出库仓库下拉选项
  const sparePartOutBoundOptionList = ref<Array<Array<WarehouseOutWarehouseAndPersonAddress>>>([])

  // 表格每行的出库仓位下拉选项
  const sparePartOutBoundPositionOptionList = ref<Array<Array<WarehousePositionOption>>>([])

  // 表格每行的配件名称
  const sparePartNameList = ref<Array<string>>([])

  // 表格每行的配件编号
  const sparePartCodeList = ref<Array<string>>([])

  // 表格每行的图片列表
  const sparePartImgFileList = ref<
    Array<Array<{ file: UploadRawFile | null; image: string; id: string }>>
  >([])

  /**
   * 设置附件列的宽度
   */
  const setAnnexColumnWidth = () => {
    let maxImageLength = Math.max(...sparePartImgFileList.value.map((item) => item.length))

    // 在图片数量小于8张时要把上传按钮的宽度计算进去
    if (maxImageLength < 8) {
      maxImageLength += 1
    }

    // 这是为了解决删剩一张图时，列宽会变得很小，导致标题会换行
    if (maxImageLength > 0) {
      annexColumnWidth.value = maxImageLength * 60 + (maxImageLength - 1) * 8 + 24
    }

    if (annexColumnWidth.value < 130) {
      annexColumnWidth.value = 130
    }
  }

  // 收支类型选项
  const incomeOrPayTypeOptional = [
    { name: '公司承担', value: 1 },
    { name: '收取客户', value: 2 },
    { name: '支付网点', value: 3 },
  ]

  /**
   * 收支类型更新事件
   * @param index - 配件索引
   */
  const handleIncomeOrPayTypeChange = (index: number) => {
    const sparePart = checkForm.value.workSpareMaterials[index]
    if (!sparePart) {
      return false
    }

    const { specId, overinsured, type } = checkForm.value.workSpareMaterials[index]
    const specOptionList = sparePartSpecOptionList.value[index]
    if (!specOptionList) {
      return false
    }

    // 提取费用项目的金额
    let price = 0
    if (checkForm.value.workSpareMaterials[index].specId) {
      const feeProject = specOptionList.find((item) => item.id === specId)
      if (feeProject) {
        price = (overinsured ? feeProject.overPrice : feeProject.price) || 0
      }
    }

    checkForm.value.workSpareMaterials[index].customerUndertakePrice = 0
    checkForm.value.workSpareMaterials[index].price = 0
    checkForm.value.workSpareMaterials[index].networkUndertakePrice = 0

    switch (type) {
      case 1:
        checkForm.value.workSpareMaterials[index].price = price
        break
      case 2:
        checkForm.value.workSpareMaterials[index].customerUndertakePrice = price
        break
      case 3:
        checkForm.value.workSpareMaterials[index].networkUndertakePrice = price
        break
    }
  }

  /**
   * 退回仓库下拉选项点击事件
   * @param item - 人员、地址、仓库信息
   */
  const handleChangeReturnWareHouse = (item: WarehouseOutWarehouseAndPersonAddress) => {
    checkForm.value.oldReceiptName = item.userName
    checkForm.value.oldReceiptPhone = item.phone
    checkForm.value.oldReceiptAddress = item.address
    checkForm.value.oldReceiptProvince = item.province
    checkForm.value.oldReceiptCity = item.city
    checkForm.value.oldReceiptArea = item.area
    checkForm.value.oldReceiptTown = item.town
    checkForm.value.storePositionId = ''
    returnWarehousePositionOptionList.value = []
    if (isEnableStorePosition(item.id, returnWarehouseOptionList.value)) {
      getReturnWarehousePositionOptionList(item.id)
    }
  }

  /**
   * 退回仓位下拉选项查询
   * @param keyword - 搜索关键字
   */
  const handleWarehousePositionOptionListSearch = _.debounce((keyword: string) => {
    getReturnWarehousePositionOptionListParam.value.name = keyword
    getReturnWarehousePositionOptionList(checkForm.value.storeId)
  }, 600)

  /**
   * 出库仓选择事件
   * @param row - 配件对象
   * @param index - 表格行索引
   */
  const handleOutBoundWarehouseChange = async (
    row: OrderAPIRequest.AuditSparePart['workSpareMaterials'][0],
    index: number,
  ) => {
    const outBoundWarehouseOptionList = sparePartOutBoundOptionList.value[index]

    // 判断是否启用仓位
    if (
      outBoundWarehouseOptionList &&
      isEnableStorePosition(row.storeId, outBoundWarehouseOptionList)
    ) {
      await getOutBoundWarehousePositionOptionList(row.storeId)
      sparePartOutBoundPositionOptionList.value[index] = outBoundWarehousePositionOptionList.value
    } else {
      handleOutBoundWarehousePositionChange(row, index)
    }
  }

  /**
   * 出库仓仓位选择事件
   * @param row - 配件对象
   * @param index - 表格行索引
   */
  const handleOutBoundWarehousePositionChange = (
    row: OrderAPIRequest.AuditSparePart['workSpareMaterials'][0],
    index: number,
  ) => {
    if (row.spareId && row.specId && row.storeId) {
      let data: {
        goodsId: string
        goodsSpecId: string
        storeId: string
        storePositionId: string
        type: 1 | 2
      } = {
        goodsId: row.spareId,
        goodsSpecId: row.specId,
        storeId: row.storeId,
        storePositionId: row.storePositionId || '',
        type: 2,
      }
      const outBoundWarehouseOptionList = sparePartOutBoundOptionList.value[index]
      if (
        outBoundWarehouseOptionList &&
        !isEnableStorePosition(row.storeId, outBoundWarehouseOptionList)
      ) {
        data.storePositionId = row.storePositionId
      }

      getGoodsStock(data).then((res) => {
        if (res && res.data.code === 20000) {
          if (res.data.data.row.id && !Number(row.price)) {
            checkForm.value.workSpareMaterials[index].price = res.data.data.row.price
          }
          // dataList.value.workSpareMaterials[index].systemStock = res.data.data.row.systemStock
        }
      })
    }
  }

  /**
   * 出库仓仓位搜素事件
   * @param keyword - 搜索关键字
   * @param index - 表格行索引
   */
  const handleOutBoundWarehousePositionOptionListSearch = _.debounce(
    async (keyword: string, index: number) => {
      const sparePart = checkForm.value.workSpareMaterials[index]
      if (sparePart) {
        getOutBoundWarehousePositionOptionListParam.value.name = keyword
        await getOutBoundWarehousePositionOptionList(sparePart.id)
        sparePartOutBoundPositionOptionList.value[index] = outBoundWarehousePositionOptionList.value
      }
    },
    600,
  )

  /**
   * 判断是否启用仓位
   * @param id - 仓库id
   * @param storePositions - 仓库下拉选项
   */
  const isEnableStorePosition = (
    id: string,
    storePositions: Array<WarehouseOutWarehouseAndPersonAddress>,
  ) => {
    if (storePositions.length <= 0) {
      return false
    }
    const storePosition = storePositions.find((item) => item.id === id)
    if (!storePosition) {
      return false
    }
    return storePosition.enableStorePosition
  }

  /**
   * 收获地址类型更新事件
   * @param val - 1、工单客户，2、网点
   */
  const handleReceiptAddressTypeChange = (val: 1 | 2) => {
    switch (val) {
      case 1:
        getWorkUserAddressData()
        break
      case 2:
        getOrderNetworkAddressData()
        break
      default:
        checkForm.value.receiptName = ''
        checkForm.value.receiptPhone = ''
        checkForm.value.receiptAddress = ''
        checkForm.value.receiptProvince = ''
        checkForm.value.receiptCity = ''
        checkForm.value.receiptArea = ''
        checkForm.value.receiptTown = ''
        singleAddressModelValue.value = {
          province: '',
          city: '',
          area: '',
          town: '',
        }
        if (singleAddressInstance.value) {
          singleAddressInstance.value.clearSelectAddr()
        }
        break
    }
  }

  /**
   * 旧件处理方式更新事件
   * @param val 1-废弃，2-旧件退回
   */
  const handleOldCopeWayChange = (val: 1 | 2) => {
    switch (val) {
      case 1:
        checkForm.value.oldReceiptName = ''
        checkForm.value.oldReceiptPhone = ''
        checkForm.value.oldReceiptAddress = ''
        checkForm.value.oldReceiptProvince = ''
        checkForm.value.oldReceiptCity = ''
        checkForm.value.oldReceiptArea = ''
        checkForm.value.oldReceiptTown = ''
        break
      case 2:
        break
    }
  }

  /**
   * 获取工单客户地址
   */
  const getWorkUserAddressData = async () => {
    try {
      const res = await getWorkUserAddress(props.orderDetail.id)
      if (res.data.code === 20000) {
        checkForm.value.userOrNetworkId = res.data.data.row.id
        checkForm.value.receiptName = res.data.data.row.name
        checkForm.value.receiptPhone = res.data.data.row.phone
        checkForm.value.receiptAddress = res.data.data.row.address
        checkForm.value.receiptProvince = res.data.data.row.province
        checkForm.value.receiptCity = res.data.data.row.city
        checkForm.value.receiptArea = res.data.data.row.area
        checkForm.value.receiptTown = res.data.data.row.town
        singleAddressModelValue.value = {
          province: checkForm.value.receiptProvince,
          city: checkForm.value.receiptCity,
          area: checkForm.value.receiptArea,
          town: checkForm.value.receiptTown,
        }
      } else {
        HMessageBox.error(res.data.message)
      }
    } catch (error) {
      HMessageBox.error('获取工单客户地址失败，请稍后重试')
    }
  }

  /**
   * 获取工单网点的地址
   */
  const getOrderNetworkAddressData = async () => {
    try {
      const res = await getOrderNetworkAddress(props.orderDetail.id)
      if (res.data.success) {
        checkForm.value.userOrNetworkId = res.data.data.row.id
        checkForm.value.receiptName = res.data.data.row.name
        checkForm.value.receiptPhone = res.data.data.row.phone
        checkForm.value.receiptAddress = res.data.data.row.address
        checkForm.value.receiptProvince = res.data.data.row.province
        checkForm.value.receiptCity = res.data.data.row.city
        checkForm.value.receiptArea = res.data.data.row.area
        checkForm.value.receiptTown = res.data.data.row.town
        singleAddressModelValue.value = {
          province: checkForm.value.receiptProvince,
          city: checkForm.value.receiptCity,
          area: checkForm.value.receiptArea,
          town: checkForm.value.receiptTown,
        }
      } else {
        HMessageBox.error(res.data.message)
      }
    } catch (error) {
      HMessageBox.error('获取网点地址失败，请稍后重试')
    }
  }

  // 保存加载
  const saveLoading = ref(false)

  const fileUploadLoading = ref(false)

  // 保存
  async function onSave() {
    if (checkForm.value.oldCopeWay == null) {
      checkForm.value.oldCopeWay = 1
    }

    if (checkForm.value.oldCopeWay == 2) {
      if (checkForm.value.workSpareMaterials.some((o) => o.status == 2)) {
        if (!checkForm.value.storeId) {
          HMessageBox.error('请选择退回的仓库！')
          return
        }
        if (
          !checkForm.value.storePositionId &&
          checkForm.value.storeId &&
          isEnableStorePosition(checkForm.value.storeId, returnWarehouseOptionList.value)
        ) {
          HMessageBox.error('请选择退回仓库的仓位！')
          return
        }
      }
    }

    for (let i = 0; i < sparePartImgFileList.value.length; i++) {
      fileUploadLoading.value = true
      const imageList = sparePartImgFileList.value[i]

      const fileList = imageList
        .filter((item) => !!item.file)
        .map((item) => item.file) as Array<UploadRawFile>
      if (fileList.length > 0) {
        const res = await orderAnnexUpload(fileList)
        sparePartImgFileList.value[i] = sparePartImgFileList.value[i].filter((item) => item.id)
        res.data.data.rows.forEach((url) => {
          sparePartImgFileList.value[i].push({
            id: '',
            file: null,
            image: url,
          })
        })
        checkForm.value.workSpareMaterials[i].images = sparePartImgFileList.value[i].map((item) => {
          return { id: item.id, image: item.image }
        })
      }
      fileUploadLoading.value = false
    }
    const res = await check()

    if (res.code === 20000) {
      HMessage.success('审核成功')
      emits('update-list')
      onCancel()
    } else {
      HMessageBox.error(res.message)
    }
    saveLoading.value = false
  }

  /**
   * 配件规格点击事件
   * @param id - 规格id
   * @param index - 操作的表格行的索引
   */
  const handlePartSpecClick = (id: string, index: number) => {
    const specOptionList = sparePartSpecOptionList.value[index]
    if (!specOptionList) {
      return false
    }

    const sparePartSpec = specOptionList.find((item) => item.id === id)
    if (!sparePartSpec) {
      return false
    }

    const price =
      (checkForm.value.workSpareMaterials[index].overinsured
        ? sparePartSpec.overPrice
        : sparePartSpec.price) || 0
    checkForm.value.workSpareMaterials[index].price = 0
    checkForm.value.workSpareMaterials[index].networkUndertakePrice = 0
    checkForm.value.workSpareMaterials[index].customerUndertakePrice = 0
    if (checkForm.value.workSpareMaterials[index].type === 1) {
      checkForm.value.workSpareMaterials[index].price = price
    }
    if (checkForm.value.workSpareMaterials[index].type === 2) {
      checkForm.value.workSpareMaterials[index].customerUndertakePrice = price
    }
    if (checkForm.value.workSpareMaterials[index].type === 3) {
      checkForm.value.workSpareMaterials[index].networkUndertakePrice = price
    }
  }

  /**
   * 上传图片事件
   * @param file - 文件
   * @param index - 配件索引
   */
  const handleUploadPicture = (file: UploadFile, index: number) => {
    if (!file.raw) {
      return false
    }

    if (!file.raw.type.includes('image')) {
      HMessageBox.error('只能上传图片类型的文件')
      return
    }

    if (sparePartImgFileList.value[index].length >= 8) {
      HMessageBox.error('最多上传8个')
      return
    }

    sparePartImgFileList.value[index].push({
      image: URL.createObjectURL(file.raw),
      file: file.raw,
      id: '',
    })

    setAnnexColumnWidth()
  }

  const onCancel = () => {
    visible.value = false
    resetCheckForm()
  }

  /**
   * 删除文件
   * @param {number} rowIndex - 操作的表格行的索引
   * @param {number} imgIndex - 文件索引
   */
  const handleDelFile = (rowIndex: number, imgIndex: number) => {
    const fileList = sparePartImgFileList.value[rowIndex]

    if (fileList && fileList[imgIndex].id) {
      HMessageBox.error('禁止删除原本附件')
      return
    }

    const imgs = sparePartImgFileList.value[rowIndex].splice(imgIndex, 1)
    if (!checkForm.value.workSpareMaterials[rowIndex].delImageIds) {
      checkForm.value.workSpareMaterials[rowIndex].delImageIds = [imgs[0].id]
    } else {
      checkForm.value.workSpareMaterials[rowIndex].delImageIds.push(imgs[0].id)
    }
    setAnnexColumnWidth()
  }

  // 是否禁用旧件处理方式选择器
  const isDisableCheckStatusSelect = ref(false)

  /**
   * 审核状态更新事件
   */
  const handleSelectCheckStatus = () => {
    let isAllReject = true
    checkForm.value.workSpareMaterials.forEach((item) => {
      if (item.status === 2) {
        isAllReject = false
      }
    })

    isDisableCheckStatusSelect.value = false
    if (isAllReject) {
      isDisableCheckStatusSelect.value = true
      checkForm.value.oldCopeWay = 1
    }
  }

  /**
   * 入库仓库下拉选项搜索事件
   * @param {string} keyword - 搜索条件
   */
  const handleReturnWarehouseOptionListSearch = _.debounce((keyword: string) => {
    getReturnWarehouseOptionListParam.value.name = keyword
    getReturnWarehouseOptionList(0)
  }, 600)

  /**
   * 配件编号输入事件
   * @param {string} code - 输入的编号
   * @param {number} sparePartIndex - 配件索引
   */
  const handleSparePartCodeInput = _.debounce(async (code: string, sparePartIndex: number) => {
    const sparePart = checkForm.value.workSpareMaterials[sparePartIndex]
    if (!sparePart) {
      return false
    }

    if (code) {
      sparePartSelectPopoverVisibleList.value[sparePartIndex] = true
      getGoodListParam.value.keyword = code
      await getGoodList()
    }
  }, 500)

  /**
   * 配件下拉选项点击事件
   * @param sparePartOption - 配件下拉选项
   * @param {number} index - 配件索引
   */
  const handleSparePartOptionClick = async (sparePartOption: GoodItem, index: number) => {
    checkForm.value.workSpareMaterials[index].specId = ''
    checkForm.value.workSpareMaterials[index].spareId = sparePartOption.id
    sparePartCodeList.value[index] = sparePartOption.code
    sparePartNameList.value[index] = sparePartOption.name
    if (sparePartOption.id) {
      const good = goodList.value.find((item) => item.id === sparePartOption.id)
      if (good) {
        await getProductSpecList(good.goodsType === 1 ? 'product' : 'material', good.id)
        const specOptionList = sparePartSpecOptionList.value[index]
        if (specOptionList && specOptionList[0]) {
          handlePartSpecClick(specOptionList[0].id, index)
        }
      }
    }
  }

  /**
   * 规格搜索事件
   */
  const handleSparePartSpecSearch = _.debounce(async (keyword: string, sparePartIndex: number) => {
    getGoodSpecParam.value.name = keyword
    const sparePart = checkForm.value.workSpareMaterials[sparePartIndex]
    if (sparePart) {
      const good = goodList.value.find((item) => item.id === sparePart.spareId)
      if (good) {
        await getProductSpecList(good.goodsType === 1 ? 'product' : 'material', good.id)
        sparePartSpecOptionList.value[sparePartIndex] = goodSpecList.value
      }
    }
  }, 600)

  /**
   * 出库仓库搜索事件
   * @param keyword - 搜索关键字
   */
  const handleOutBoundWarehouseOptionListSearch = _.debounce(
    async (keyword: string, index: number) => {
      getOutBoundWarehouseOptionListParam.value.name = keyword
      if (info.value && info.value.networkSpareType === 1 && info.value.type === 2) {
        await getOutBoundWarehouseOptionList(1)
      } else {
        await getOutBoundWarehouseOptionList(0)
      }
      sparePartOutBoundOptionList.value[index] = outBoundWarehouseOptionList.value
    },
    600,
  )

  /**
   * 表单初始化
   */
  const formInit = async () => {
    if (!props.partsId) {
      return
    }

    await getInfo(props.partsId)
    checkForm.value = {
      id: info.value.id,
      oldCopeWay: info.value.oldCopeWay === 0 ? 2 : info.value.oldCopeWay,
      oldReceiptAddress: '',
      oldReceiptArea: '',
      oldReceiptCity: '',
      oldReceiptName: '',
      oldReceiptPhone: '',
      oldReceiptProvince: '',
      oldReceiptTown: '',
      receiptAddrType: info.value.receiptAddrType,
      receiptAddress: info.value.receiptAddress,
      receiptArea: info.value.receiptArea,
      receiptCity: info.value.receiptCity,
      receiptName: info.value.receiptName,
      receiptPhone: info.value.receiptPhone,
      receiptProvince: info.value.receiptProvince,
      receiptTown: info.value.receiptTown,
      remark: info.value.applyRemark,
      storeId: '',
      storePositionId: '',
      userOrNetworkId: info.value.userOrNetworkId,
      workSpareMaterials: [],
    }

    if (checkForm.value.receiptAddrType === 1) {
      await getWorkUserAddressData()
    }

    if (checkForm.value.receiptAddrType === 2) {
      await getOrderNetworkAddressData()
    }
  }

  /**
   * 表格初始化
   */
  const tableInit = async () => {
    if (!props.partsId) {
      return false
    }
    await getList(props.partsId)
    checkForm.value.workSpareMaterials = list.value.map((item) => {
      return {
        customerUndertakePrice: item.customerUndertakePrice || 0,
        delImageIds: [],
        id: item.id,
        images: item.images,
        networkUndertakePrice: item.networkUndertakePrice || 0,
        overinsured: item.overinsured,
        price: item.price,
        qty: item.qty,
        remark: item.remark,
        spareId: item.spareId,
        specId: item.specId,
        status: 2,
        storeId: '',
        storePositionId: '',
        type: item.type,
      }
    })

    sparePartImgFileList.value = checkForm.value.workSpareMaterials.map((sparePart) => {
      return sparePart.images.map((img) => {
        return {
          file: null,
          image: img.image,
          id: img.id,
        }
      })
    })

    setAnnexColumnWidth()
    sparePartSelectPopoverVisibleList.value = checkForm.value.workSpareMaterials.map(() => false)
    for (let i = 0; i < list.value.length; i++) {
      getGoodListParam.value.keyword = list.value[i].applySpareCode
      await getGoodList()
      const good = goodList.value.find((item) => item.id === list.value[i].spareId)
      if (good) {
        await getProductSpecList(
          good.goodsType === 1 ? 'product' : 'material',
          list.value[i].spareId,
        )
        sparePartSpecOptionList.value[i] = goodSpecList.value
        sparePartNameList.value[i] = good.name
        sparePartCodeList.value[i] = good.code
      }

      if (info.value && info.value.networkSpareType === 1 && info.value.type === 2) {
        await getWarehouse(props.orderDetail.networkId)
        await getOutBoundWarehouseOptionList(1)
        // 如果申请类型是外部配件，网点配件类型是网点仓，那么仓库就要拿网点仓的，并且不能改
        if (info.value.networkSpareType === 1 && info.value.type === 2) {
          checkForm.value.workSpareMaterials = checkForm.value.workSpareMaterials.map((item) => {
            item.storeId = warehouse.value.storeId
            return item
          })
        }
      } else {
        await getOutBoundWarehouseOptionList(0)
      }
      sparePartOutBoundOptionList.value[i] = outBoundWarehouseOptionList.value
    }
  }

  /**
   * 弹窗初始化
   */
  const init = async () => {
    if (visible.value && props.partsId) {
      await formInit()
      await tableInit()
    }
  }

  watch(visible, () => {
    init()
  })
</script>

<template>
  <h-drawer
    v-model="visible"
    :width="1200"
    unit="px"
    :loading="
      checkLoading || getInfoLoading || getListLoading || fileUploadLoading || getGoodListLoading
    "
    @close="onCancel"
  >
    <template #title>
      <div class="drawer_title_container">
        <span>审核配件</span>
        <HStatus type="warning" :height="20">待审核</HStatus>
      </div>
    </template>
    <div class="body">
      <div class="form">
        <div class="title">基本信息</div>
        <div class="info_list">
          <div class="info_item">
            <div class="label">配件编号:</div>
            <div class="value">{{ info.code }}</div>
          </div>
          <div class="info_item">
            <div class="label">工单单号:</div>
            <div class="value">{{ info.workNo }}</div>
          </div>
          <div class="info_item">
            <div class="label">申请类型:</div>
            <div class="value">{{ info.type === 1 ? '公司配件' : '外部配件' }}</div>
          </div>
          <div v-if="info.type === 2" class="info_item">
            <div class="label">网点配件类型:</div>
            <div class="value">{{ info.networkSpareType === 1 ? '网点仓' : '自购配件' }}</div>
          </div>
        </div>
        <div class="content">
          <el-form label-position="top" :model="checkForm">
            <div class="warehouse_back_container">
              <!-- 收货地址类型 -->
              <el-form-item label="收货地址类型" class="address_type">
                <el-select
                  v-model="checkForm.receiptAddrType"
                  clearable
                  placeholder="收货地址类型"
                  @change="handleReceiptAddressTypeChange"
                >
                  <el-option label="工单客户" :value="1" />
                  <el-option label="网点" :value="2" />
                </el-select>
              </el-form-item>

              <!-- 旧件处理方式 -->
              <el-form-item label="旧件处理方式" class="old_handle_method">
                <el-select
                  v-model="checkForm.oldCopeWay"
                  placeholder="旧件处理方式"
                  :disabled="isDisableCheckStatusSelect"
                  @change="handleOldCopeWayChange"
                >
                  <el-option label="废弃" :value="1" />
                  <el-option label="旧件退回" :value="2" />
                </el-select>
              </el-form-item>

              <!-- 退回仓库 -->
              <el-form-item v-if="checkForm.oldCopeWay === 2" label="退回仓库">
                <el-select
                  v-model="checkForm.storeId"
                  :loading="getReturnWarehouseOptionListLoading"
                  placeholder="请选择仓库"
                  filterable
                  :filter-method="handleReturnWarehouseOptionListSearch"
                >
                  <el-option
                    v-for="item in returnWarehouseOptionList"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                    @click="handleChangeReturnWareHouse(item)"
                  />
                </el-select>
                <div v-if="checkForm.storeId" class="back_warehouse_info_list">
                  <div class="info_item">
                    <div class="label">姓名:</div>
                    <div class="value">{{ checkForm.oldReceiptName }}</div>
                  </div>
                  <div class="info_item">
                    <div class="label">手机号:</div>
                    <div class="value">{{ checkForm.oldReceiptPhone }}</div>
                  </div>
                  <div class="info_item">
                    <div class="label">仓库地址:</div>
                    <div class="value">
                      {{
                        checkForm.oldReceiptProvince +
                        checkForm.oldReceiptCity +
                        checkForm.oldReceiptArea +
                        checkForm.oldReceiptTown +
                        checkForm.oldReceiptAddress
                      }}
                    </div>
                  </div>
                </div>
              </el-form-item>

              <el-form-item
                v-if="
                  isEnableStorePosition(checkForm.storeId, returnWarehouseOptionList) &&
                  checkForm.oldCopeWay === 2
                "
                label="退回仓位"
              >
                <el-select
                  v-model="checkForm.storePositionId"
                  :loading="getReturnWarehousePositionOptionListLoading"
                  placeholder="请选择退回仓位"
                  :filter-method="handleWarehousePositionOptionListSearch"
                >
                  <el-option
                    v-for="item in returnWarehousePositionOptionList"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </el-form-item>
            </div>

            <div class="personal_phone_container">
              <!-- 收货人姓名 -->
              <el-form-item label="收货人姓名" class="person_name">
                <el-input v-model.trim="checkForm.receiptName" clearable placeholder="收货人姓名" />
              </el-form-item>

              <!-- 收货人手机号 -->
              <el-form-item label="收货人手机号" class="phone">
                <el-input
                  v-model.trim.number="checkForm.receiptPhone"
                  :maxlength="11"
                  clearable
                  placeholder="收货人手机号"
                />
              </el-form-item>

              <el-form-item label="审核备注" class="remark">
                <el-input
                  v-model.trim="checkForm.remark"
                  clearable
                  maxlength="200"
                  placeholder="填写备注信息"
                  show-word-limit
                  size="small"
                  type="textarea"
                  resize="both"
                />
              </el-form-item>
            </div>

            <div class="address_container">
              <el-form-item label="收货人地址">
                <SingleAddress ref="singleAddressInstance" :address="singleAddressModelValue" />
              </el-form-item>
              <el-form-item label="详细地址">
                <el-input
                  v-model.trim="checkForm.receiptAddress"
                  :rows="2"
                  clearable
                  maxlength="200"
                  placeholder="收货人详细地址"
                  show-word-limit
                  size="small"
                  type="textarea"
                  resize="both"
                />
              </el-form-item>
            </div>
          </el-form>
        </div>
      </div>
      <div class="table">
        <el-table
          :border="true"
          :data="checkForm.workSpareMaterials"
          resizable
          stripe
          height="100%"
        >
          <el-table-column fixed="left" label="序号" width="50" type="index" :align="'center'" />

          <!-- 收支类型 -->
          <el-table-column label="收支类型" width="150">
            <template #default="{ row, $index }">
              <el-select
                v-model="row.type"
                placeholder="收支类型"
                @change="handleIncomeOrPayTypeChange($index)"
              >
                <el-option
                  v-for="item in incomeOrPayTypeOptional"
                  :key="item.value"
                  :value="item.value"
                  :label="item.name"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 配件编号 -->
          <el-table-column label="配件编号" width="200">
            <template #default="{ $index }">
              <el-popover
                placement="bottom-start"
                :width="700"
                :visible="sparePartSelectPopoverVisibleList[$index]"
                popper-style="padding: 0;"
                :show-arrow="false"
              >
                <template #reference>
                  <el-input
                    v-model.trim="sparePartCodeList[$index]"
                    placeholder="请输入配件编号"
                    @input="(keyword: string) => handleSparePartCodeInput(keyword, $index)"
                    @blur="sparePartSelectPopoverVisibleList[$index] = false"
                  />
                </template>

                <el-table
                  v-loading="getGoodListLoading"
                  :border="true"
                  :data="goodList"
                  max-height="400"
                  @row-click="(row: GoodItem) => handleSparePartOptionClick(row, $index)"
                >
                  <!-- 序号 -->
                  <el-table-column type="index" label="序号" :align="'center'" width="50" />

                  <!-- 物料编号 -->
                  <el-table-column prop="code" label="物料编号" width="140" />

                  <!-- 物料名称 -->
                  <el-table-column
                    show-overflow-tooltip
                    prop="name"
                    label="物料名称"
                    min-width="160"
                  />

                  <!-- 物料分类 -->
                  <el-table-column prop="type" label="物料分类" width="120" />
                </el-table>
              </el-popover>
            </template>
          </el-table-column>

          <!-- 配件名称 -->
          <el-table-column label="配件名称" width="160">
            <template #default="{ $index }">
              <el-input :model-value="sparePartNameList[$index]" disabled />
            </template>
          </el-table-column>

          <!-- 规格 -->
          <el-table-column label="规格" width="180">
            <template #default="{ row, $index }">
              <el-select
                v-model="row.specId"
                :loading="getGoodSpecLoading"
                placeholder="请选择"
                filterable
                :filter-method="(keyword: string) => handleSparePartSpecSearch(keyword, $index)"
                @change="(id: string) => handlePartSpecClick(id, $index)"
              >
                <el-option
                  v-for="item in sparePartSpecOptionList[$index]"
                  :key="item.name"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </template>
          </el-table-column>

          <!-- 申请数量 -->
          <el-table-column label="申请数量" width="90">
            <template #default="{ row }">
              <el-input v-model.trim.number="row.qty" clearable placeholder="数量" />
            </template>
          </el-table-column>

          <!-- 公司承担 -->
          <el-table-column label="公司承担费用单价" width="140">
            <template #default="{ row }">
              <el-input
                v-model.trim="row.price"
                clearable
                style="border-radius: 2px"
                :disabled="row.type !== 1"
              />
            </template>
          </el-table-column>

          <!-- 客户承担 -->
          <el-table-column label="收取客户费用单价" width="140">
            <template #default="{ row }">
              <el-input
                v-model.trim="row.customerUndertakePrice"
                clearable
                style="border-radius: 2px"
                :disabled="row.type !== 2"
              />
            </template>
          </el-table-column>

          <!-- 网点承担 -->
          <el-table-column label="支付网点费用单价" width="140">
            <template #default="{ row }">
              <el-input
                v-model.trim="row.networkUndertakePrice"
                clearable
                style="border-radius: 2px"
                :disabled="row.type !== 3"
              />
            </template>
          </el-table-column>

          <!-- 出库仓库 -->
          <template v-if="info && [1, 2].includes(info.networkSpareType)">
            <el-table-column label="出库仓库" width="180">
              <template #default="{ row, $index }">
                <el-select
                  v-model="row.storeId"
                  :loading="getOutBoundWarehouseOptionListLoading"
                  placeholder="请选择"
                  :disabled="info.type === 2 && info.networkSpareType === 1"
                  filterable
                  :filter-method="(keyword: string) => handleOutBoundWarehouseOptionListSearch(keyword, $index)"
                  @change="handleOutBoundWarehouseChange(row, $index)"
                >
                  <el-option
                    v-for="item in sparePartOutBoundOptionList[$index]"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 仓位 -->
            <el-table-column label="仓位" width="120">
              <template #default="{ row, $index }">
                <el-select
                  v-model="row.storePositionId"
                  :disabled="
                    !isEnableStorePosition(row.storeId, sparePartOutBoundOptionList[$index] || [])
                  "
                  :loading="getOutBoundWarehousePositionOptionListLoading"
                  placeholder="请选择"
                  filterable
                  :filter-method="(keyword: string) => handleOutBoundWarehousePositionOptionListSearch(keyword, $index)"
                  @change="handleOutBoundWarehousePositionChange(row, $index)"
                >
                  <el-option
                    v-for="item in sparePartOutBoundPositionOptionList[$index] || []"
                    :key="item.name"
                    :label="item.name"
                    :value="item.id"
                  />
                </el-select>
              </template>
            </el-table-column>

            <!-- 即时库存 -->
            <el-table-column label="即时库存" width="180">
              <template #default="{ row }">
                <span>{{ row.systemStock }}</span>
              </template>
            </el-table-column>
          </template>

          <!-- 备注 -->
          <el-table-column label="备注" max-width="150" min-width="140">
            <template #default="{ row }">
              <el-input v-model.trim="row.remark" clearable placeholder="填写备注" />
            </template>
          </el-table-column>

          <!-- 审核状态 -->
          <el-table-column label="审核" width="120" fixed="right" :align="'center'">
            <template #default="{ row }">
              <el-select
                v-model="row.status"
                filterable
                placeholder="审核"
                @change="handleSelectCheckStatus"
              >
                <el-option label="通过" :value="2" />
                <el-option label="驳回" :value="3" />
              </el-select>
            </template>
          </el-table-column>

          <!-- 附件 -->
          <el-table-column :width="annexColumnWidth" label="附件(最多上传8个)">
            <template #default="{ row, $index }">
              <div class="file_list">
                <template v-for="(img, index) in sparePartImgFileList[$index]" :key="index">
                  <h-image
                    :width="60"
                    :height="37.5"
                    :src="img.image"
                    :initial-index="index"
                    :preview-src-list="
                      (sparePartImgFileList[$index] || []).map((item) => item.image)
                    "
                    fit="scale-down"
                    :padding="2"
                    :show-del-btn="!img.id"
                    :mask-btn-gap="3"
                    @del="handleDelFile($index, index)"
                  />
                </template>
                <h-image
                  v-if="row.images.length < 8"
                  :src="uploadPlaceholderImg"
                  :width="60"
                  :height="37.5"
                  :padding="2"
                >
                  <el-upload
                    :auto-upload="false"
                    :on-change="(file) => handleUploadPicture(file, $index)"
                    :show-file-list="false"
                    accept="image/*"
                    action="#"
                    multiple
                  >
                    <div style="height: 35.5px; line-height: 35.5px">
                      <i class="iconfont icon-img-upload" style="color: #fff; font-size: 24px"></i>
                    </div>
                  </el-upload>
                </h-image>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <template #footer>
      <HButton is-modal type="primary" :disabled="$route.query.isArchive == 'true'" @click="onSave">
        审核
      </HButton>
      <HButton is-modal @click="onCancel">取消</HButton>
    </template>
  </h-drawer>
</template>

<style lang="scss" scoped>
  .file_list {
    display: flex;
    column-gap: 8px;

    :deep(.el-upload) {
      width: 40px;
      height: 40px;
    }
  }

  .select_header {
    display: flex;
    gap: 5px;

    :deep(.el-input__wrapper) {
      height: 26px !important;
      font-size: 12px !important;
    }
  }

  .drawer_title_container {
    display: flex;
    align-items: center;
    column-gap: 10px;
  }

  .body {
    height: 100%;
    display: flex;
    flex-direction: column;
    row-gap: 8px;

    .form {
      display: flex;
      flex-direction: column;
      row-gap: 8px;

      .title {
        padding-left: 6px;
        border-left: 3px solid $primaryColor;
        font-size: 14px;
        font-weight: bold;
      }

      .info_list {
        display: flex;
        padding: 0 9px;
        column-gap: 32px;
        flex-wrap: wrap;

        .info_item {
          display: flex;
          column-gap: 5px;

          .label {
            color: #606266;
          }
        }
      }

      .content {
        padding: 0 9px;

        :deep(.el-form) {
          display: grid;
          grid-template-columns: repeat(3, 1fr);
          column-gap: 72px;
          row-gap: 12px;

          .warehouse_back_container,
          .personal_phone_container,
          .address_container {
            display: flex;
            flex-direction: column;
            row-gap: 12px;

            .el-form-item {
              width: 250px;

              .el-form-item__label {
                height: 16px;
                line-height: 16px;
                margin-bottom: 3px;
              }

              .el-form-item__content {
                .back_warehouse_info_list {
                  display: flex;
                  column-gap: 12px;
                  width: 320px;
                  flex-wrap: wrap;
                  flex-direction: column;
                  margin-top: 3px;

                  .info_item {
                    display: flex;
                    column-gap: 5px;
                    align-items: flex-start;

                    .label {
                      color: #606266;
                      white-space: nowrap;
                      height: 16px;
                      line-height: 16px;
                      width: 50px;
                      text-align: right;
                    }

                    .value {
                      line-height: 16px;
                    }
                  }
                }

                .el-textarea {
                  width: auto;

                  .el-textarea__inner {
                    min-width: 250px !important;
                    max-width: 550px !important;
                    min-height: 28px !important;
                    max-height: 100px !important;
                    height: 28px;
                  }
                }
              }
            }
          }

          .address_container {
            .el-form-item {
              min-width: 430px;

              .el-form-item__content {
                display: flex;
                column-gap: 5px;
                flex-wrap: nowrap;
                align-items: flex-start;

                .el-cascader {
                  width: 100% !important;
                }

                .el-textarea {
                  width: 100% !important;

                  .el-textarea__inner {
                    width: 100% !important;
                    min-height: 28px !important;
                    max-height: 190px !important;
                    height: 28px;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
</style>
